package com.yuntu.aop;

import com.yuntu.annotation.AuthCheck;
import com.yuntu.demo.constant.UserConstant;
import com.yuntu.demo.entity.User;
import com.yuntu.demo.vo.LoginUserVO;
import com.yuntu.exception.ErrorCode;
import com.yuntu.exception.ThrowUtils;
import com.yuntu.exception.bizException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Aspect
@Component
public class AuthIntercepter {
    /**
     * 拦截，校验权限
     * @param point 切入点
     * @param authCheck 权限验证注解
     * @return
     * @throws Throwable
     */
    @Around("@annotation(authCheck)")
    public Object intercept(ProceedingJoinPoint point, AuthCheck authCheck) throws Throwable {
        String role = authCheck.mustRole();
        //没有设置权限，放行
        if("".equals(role)||role==null) {
            return point.proceed();
        }
        //设置权限了，判断权限是否足够
        //获取登录的数据
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        LoginUserVO attribute = (LoginUserVO) session.getAttribute(UserConstant.USER_LOGIN_STATE);
            ThrowUtils.throwIf(attribute==null,ErrorCode.NOT_LOGIN_ERROR);
        //设置的管理员权限,自己为用户
        if(role.equals(UserConstant.ADMIN_ROLE)&&attribute.getUserRole().equals(UserConstant.DEFAULT_ROLE)) {
            throw new bizException(-2,"权限不足");
        }
        //放行
        return point.proceed();
    }
}
